package com.lazyframework.security.web.extra.weixin;

import com.lazyframework.security.web.JwtClients;
import com.lazyframework.security.web.authentication.AuthenticationManager;
import com.lazyframework.security.web.authentication.UserDetailsService;
import com.lazyframework.security.web.configuration.HttpSecurity;
import com.lazyframework.security.web.configuration.SecurityConfigurerAdapter;
import org.springframework.util.Assert;

import javax.servlet.Filter;

public class OpenIDAuthenticationConfigurer extends SecurityConfigurerAdapter<Filter, HttpSecurity> {

    private String appid;

    private String secret;

    private JwtClients jwtClients;

    private UserDetailsService userDetailsService;

    public OpenIDAuthenticationConfigurer appid(String appid) {
        this.appid = appid;
        return this;
    }

    public OpenIDAuthenticationConfigurer secret(String secret) {
        this.secret = secret;
        return this;
    }

    public OpenIDAuthenticationConfigurer jwtClients(JwtClients jwtClients) {
        this.jwtClients = jwtClients;
        return this;
    }

    public OpenIDAuthenticationConfigurer userDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
        return this;
    }

    @Override
    public void configure(HttpSecurity builder) {
        Assert.notNull(appid, "Weixin appid can't be null.");
        Assert.notNull(secret, "Weixin secret can't be null.");

        OpenIDAuthenticationFilter filter = new OpenIDAuthenticationFilter();

        AuthenticationManager authenticationManager = builder.authenticationManager();
        OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
        provider.setAppid(appid);
        provider.setSecret(secret);
        provider.setUserDetailsService(userDetailsService);
        authenticationManager.registerProvider(provider);

        filter.setJwtClients(jwtClients);
        filter.setAuthenticationManager(authenticationManager);

        builder.addFilter(filter);
    }

}
